import zipfile
import os
import time


def unpackZip(inputDir, outputDir):
    # 第一层解压
    for file in os.listdir(inputDir):
        print(file)
        try:
            ext = file.split('.')[-1]
            fileName = file.split('.')[0]
            if(ext == 'zip'):
                print('------------------------------------------------')
                with zipfile.ZipFile(inputDir+file) as zf:
                    print('unpack %s ' % fileName)
                    zf.extractall(outputDir)
                    # 第二层解压
                    for file in os.listdir(outputDir):
                        ext = file.split('.')[-1]
                        fileName = file.split('.')[0]
                        if(ext == 'zip'):
                            print('--------------------')
                            with zipfile.ZipFile(outputDir+file) as zf:
                                print('unpack %s ' % fileName)
                                zf.extractall(outputDir)
                            os.remove(outputDir+file)
        except Exception as e:
            log('%s' % file)
            log('{}\n'.format(e))


def createLogTxt(logDir):
    '''
    根据现在的时间生成日志文件
    logDir:日志文件目录
    return:logFile 返回log文件路径(目录加文件名)
    '''
    logTxtName = time.strftime("%Y-%m-%d %H_%M_%S", time.localtime())
    global logFile
    logFile = logDir+logTxtName+'.txt'
    log('__log init__\n')


def log(info):
    '''
    记录日志
    logFile 日志文件路径
    '''
    print(info)
    timeStr = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
    # 以日期来创建log文件
    with open(logFile, "a") as f:
        f.write('{}_____{}\n'.format(timeStr, info))


def mkdir(path):
    folder = os.path.exists(path)
    if not folder:
        os.makedirs(path)
        print('mkdir %s create OK' % (path))
    else:
        print('mkdir %s already exist' % (path))


if __name__ == "__main__":
    inputDir = './Download_Dem/'
    outputDir = './tif/'
    logDir = './log/'

    mkdir(outputDir)
    mkdir(logDir)
    createLogTxt(logDir)

    unpackZip(inputDir, outputDir)
